<?php

/*

	Copyright © 2011 Mike Bennett <mike@kereru.com>

	This file is part of Tazu-Time.

    Tazu-Time is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    any later version.

    Tazu-Time is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Tazu-Time.  If not, see <http://www.gnu.org/licenses/>.
    
*/



//$e = get_loaded_extensions();
//array_dump($e);

class Db {

	// Timesheets database
	var $db_path = FALSE;					// DB file name
	var $db_file = FALSE;					// DB file name
	var $db_ext = FALSE;
	var $dsn = FALSE;
	var $filename = FALSE;

	var $db_ver = '0.9';						// Database version

	
	function __construct($data_file=FALSE) {

		$this->db_path = './';
		$this->db_file = 'timesheets';
		$this->db_ext = '.db';

		if ( $data_file ) {
			$this->db_path = dirname($data_file).'/';
			$filename = basename($data_file);
			$parts = explode('.',$filename);
			$this->db_file = $parts[0];
			$this->db_ext = '.'.$parts[1];
		}


		$this->dsn = sprintf("sqlite:%s%s%s",$this->db_path,$this->db_file,$this->db_ext);
		$this->filename = sprintf("%s%s%s",$this->db_path,$this->db_file,$this->db_ext);

		$this->database_check();	



	}

	function error($msg) {
		platform::error_popup($msg,'Timesheet database error');
	}
	

	
	/* Check database structure */
	function database_check() {

	}
	

	function getDBVersion() {

		$ver = FALSE;
		
		try {
		
			
			$db = new PDO($this->dsn);

			$qry = "SELECT * FROM status WHERE param='db_ver' LIMIT 1;";
//			$result = $db->query($qry, PDO::FETCH_ASSOC);


		   foreach ($db->query($qry, PDO::FETCH_ASSOC) as $row) {
				$ver = trim($row['value']);
		   }


			$db = null;
			

		} catch (PDOException $e) {
		   $this->error($e->getMessage());
		}

		return( $ver );

	}


	function execute($qry,$dsn=FALSE) {

		if ( ! $dsn ) $dsn = $this->dsn;

		try {
			$db = new PDO($dsn);
			$result = $db->exec($qry);
			$db = null;
			return( $result );			

		} catch (PDOException $e) {
		   $this->error($e->getMessage());
			return;
		}

	}

	function insert($qry,$dsn=FALSE) {

		if ( ! $dsn ) $dsn = $this->dsn;

		try {
			$db = new PDO($dsn);
			$result = $db->exec($qry);
			$id = $db->lastInsertId();
			$db = null;
			return( $id );			

		} catch (PDOException $e) {
		   $this->error($e->getMessage());
			return;
		}

	}
	

	function rows($qry,$cols=FALSE,$dsn=FALSE) {

		if ( ! $dsn ) $dsn = $this->dsn;

//echo $qry."\n";

		try {
		
			$db = new PDO($dsn);
			$result = array();

			$i = 0;
			$r = $db->query($qry, PDO::FETCH_ASSOC);
			
			if ( $r ) {
			   foreach ($db->query($qry, PDO::FETCH_ASSOC) as $row) {
	//print_r($row);
			   		if ( is_array($cols) ) {
			   			foreach ( $cols as $col ) {
			   				$result[$i][] = $row[$col];
			   				$result[$i][$col] = $row[$col];
			   			}
		   				$i++;
			   		}
			   		else {
						// As in table
						$result[] = $row;
					}
			   }
			}

			$db = null;
			
			if ( sizeof($result) == 0 ) $result = FALSE;
			return( $result );			

		} catch (PDOException $e) {
		   $this->error($e->getMessage());
			return;
		}

	}
	
	function col($id,$table,$col,$dsn=FALSE) {

		if ( ! $dsn ) $dsn = $this->dsn;

		try {
		
			$db = new PDO($dsn);

			$qry = sprintf("SELECT * FROM %s WHERE id='%s';",$table,$id);
			$result = FALSE;

		   foreach ($db->query($qry, PDO::FETCH_ASSOC) as $row) {
				$result = trim($row[$col]);
		   }

			$db = null;
			return($result);			

		} catch (PDOException $e) {
		   $this->error($e->getMessage());
			return;
		}

	}


	function timestamp2unix($timestamp) {
		$y = substr($timestamp,0,4);
		$m = substr($timestamp,5,2);
		$d = substr($timestamp,8,2);
		$h = substr($timestamp,11,2);
		$i = substr($timestamp,14,2);
		$s = substr($timestamp,17,2);
		
		$u = mktime($h,$i,$s,$m,$d,$y);
		return( $u );
	}

	// Input unix time to displayed day and time
	function unix2timestamp($u) {
		return( @ date("Y-m-d H:i:s",$u) );
	}



	// Input unix time to displayed day and time
	function day_time($u) {
		return( @ date("D d M Y H:i",$u) );
	}

	// Format total seconds for display
	function elapsed($secs) {

		$secs = $this->rnd_secs($secs);

		$hours = floor( $secs / 3600 );
		$secs = fmod( $secs , 3600 );
		

		$mins = floor( $secs / 60);
		
		$result = sprintf("%02d:%02d", $hours, $mins);
		
		return( $result );
	
	}



	function rnd_secs($secs) {

		$hours = floor( $secs / 3600 );
		$secs = fmod( ($secs*1) , 3600 );
		

		$mins = floor( $secs / 60);
		
		$secs = fmod( $secs , 60 );
		if ( $secs > 0 ) $mins++;			// Round up to nearest minute
		
		$result = ($hours*3600) + ($mins*60);

		return( $result );
	
	}


	
	function close() {
		return;		
	}

	function csv_escape($s){
	        if (strpos($s, '"'))
	                return '"'.str_replace('"','""',$s).'"';
	        else if (strpos($s,',')||strpos($s,"\n"))
	                return '"'.$s.'"';
	        else
	                return $s;
	}


}

?>